<!-- views/reports/StatisticsReport.vue -->
<template>
  <div class="statistics-report">
    <!-- 报告头部 -->
    <el-card class="report-header">
      <template #header>
        <div class="header-content">
          <div class="header-left">
            <h2>
              <el-icon class="title-icon"><DataAnalysis /></el-icon>
              统计分析
            </h2>
            <div class="report-info">
              <el-tag type="success">自动生成</el-tag>
              <span class="last-update">最后更新: {{ lastUpdate }}</span>
            </div>
          </div>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="loadReport"
            />
            <el-button type="primary" :icon="Refresh" @click="generateReport" :loading="loading">
              生成报告
            </el-button>
            <el-button :icon="Download" @click="exportReport">
              导出报告
            </el-button>
          </div>
        </div>
      </template>
    </el-card>

    <!-- 销售统计概览 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#1890ff' }">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatCurrency(statistics.totalSales) }}</div>
              <div class="stat-label">总销售额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#52c41a' }">
              <el-icon><ShoppingBag /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ formatNumber(statistics.orderCount) }}</div>
              <div class="stat-label">订单总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#722ed1' }">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ formatNumber(statistics.customerCount) }}</div>
              <div class="stat-label">客户数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#fa8c16' }">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.avgOrderValue }}</div>
              <div class="stat-label">客单价</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售趋势分析</span>
              <el-dropdown @command="handleChartPeriodChange">
                <el-button link>
                  {{ chartPeriodText }}<el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="7">近7天</el-dropdown-item>
                    <el-dropdown-item command="30">近30天</el-dropdown-item>
                    <el-dropdown-item command="90">近90天</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <div class="chart-container">
            <div ref="salesChartRef" class="chart-placeholder">销售趋势图表</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>产品销售排行</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="productChartRef" class="chart-placeholder">产品销售排行图表</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细分析 -->
    <el-row :gutter="20" class="analysis-section">
      <el-col :span="12">
        <el-card class="analysis-card">
          <template #header>
            <div class="card-header">
              <span>客户分析</span>
            </div>
          </template>
          <div class="analysis-content">
            <el-table :data="customerAnalysis" style="width: 100%">
              <el-table-column prop="level" label="客户等级" width="100" />
              <el-table-column prop="count" label="客户数" width="100" />
              <el-table-column prop="salesAmount" label="销售金额">
                <template #default="{ row }">
                  ¥{{ formatCurrency(row.salesAmount) }}
                </template>
              </el-table-column>
              <el-table-column prop="percentage" label="占比">
                <template #default="{ row }">
                  {{ row.percentage }}%
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="analysis-card">
          <template #header>
            <div class="card-header">
              <span>区域销售分析</span>
            </div>
          </template>
          <div class="analysis-content">
            <el-table :data="regionAnalysis" style="width: 100%">
              <el-table-column prop="region" label="区域" width="120" />
              <el-table-column prop="orderCount" label="订单数" width="100" />
              <el-table-column prop="salesAmount" label="销售金额">
                <template #default="{ row }">
                  ¥{{ formatCurrency(row.salesAmount) }}
                </template>
              </el-table-column>
              <el-table-column prop="growth" label="增长率">
                <template #default="{ row }">
                  <span :class="row.growth >= 0 ? 'growth-positive' : 'growth-negative'">
                    {{ row.growth >= 0 ? '+' : '' }}{{ row.growth }}%
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from '@vue/runtime-core'
import { 
  ElMessage, 
  ElNotification 
} from 'element-plus'
import { 
  DataAnalysis,
  Refresh, 
  Download, 
  TrendCharts,
  ShoppingBag,
  User,
  Star,
  ArrowDown
} from '@element-plus/icons-vue'

// 导入API
import { statisticsAPI } from '@/api/statistics'

// 数据模型
interface Statistics {
  totalSales: number
  orderCount: number
  customerCount: number
  avgOrderValue: string
}

interface CustomerAnalysis {
  level: string
  count: number
  salesAmount: number
  percentage: number
}

interface RegionAnalysis {
  region: string
  orderCount: number
  salesAmount: number
  growth: number
}

// 响应式数据
const dateRange = ref<string[]>([])
const loading = ref(false)
const lastUpdate = ref('')

const statistics = ref<Statistics>({
  totalSales: 0,
  orderCount: 0,
  customerCount: 0,
  avgOrderValue: '0.00'
})

const customerAnalysis = ref<CustomerAnalysis[]>([])
const regionAnalysis = ref<RegionAnalysis[]>([])

const chartPeriod = ref(30)
const salesChartRef = ref<HTMLElement | null>(null)
const productChartRef = ref<HTMLElement | null>(null)

// 方法
const formatCurrency = (amount: number): string => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const formatNumber = (num: number): string => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString()
}

const getChartPeriodText = (period: number): string => {
  const map: Record<number, string> = {
    7: '近7天',
    30: '近30天',
    90: '近90天'
  }
  return map[period] || '近30天'
}

const loadReport = async () => {
  loading.value = true
  try {
    // 调用API获取统计分析数据
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }
    
    const result = await statisticsAPI.getStatisticsAnalysis(params)
    
    if (result.success && result.data) {
      // 更新统计数据
      statistics.value = {
        totalSales: result.data.statistics.totalSales || 0,
        orderCount: result.data.statistics.orderCount || 0,
        customerCount: result.data.statistics.customerCount || 0,
        avgOrderValue: result.data.statistics.avgOrderValue || '0.00'
      }
      
      // 更新客户分析数据
      customerAnalysis.value = result.data.customerAnalysis || []
      
      // 更新区域分析数据
      regionAnalysis.value = result.data.regionAnalysis || []
      
      // 更新时间
      lastUpdate.value = new Date().toLocaleString('zh-CN')
      
      ElMessage.success('统计分析数据加载成功')
    } else {
      ElMessage.error(result.message || '获取统计分析数据失败')
    }
  } catch (error) {
    ElMessage.error('统计分析数据加载失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const generateReport = async () => {
  await loadReport()
}

const exportReport = () => {
  // 模拟导出报告
  ElMessage.success('统计分析报告导出成功!')
}

const handleChartPeriodChange = (period: number) => {
  chartPeriod.value = period
  ElMessage.info(`切换到${getChartPeriodText(period)}视图`)
}

// 组件挂载时加载数据
onMounted(() => {
  // 设置默认日期范围为最近30天
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  
  dateRange.value = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]
  
  // 加载初始数据
  loadReport()
})
</script>

<style scoped lang="scss">
.statistics-report {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
  
  .report-header {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-left {
        h2 {
          margin: 0;
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          display: flex;
          align-items: center;
          gap: 8px;
          
          .title-icon {
            color: #409eff;
          }
        }
        
        .report-info {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-top: 8px;
          
          .last-update {
            font-size: 14px;
            color: #909399;
          }
        }
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
        align-items: center;
      }
    }
  }
  
  .stats-overview {
    margin-bottom: 20px;
    
    .stat-card {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
      }
      
      .stat-content {
        display: flex;
        align-items: center;
        padding: 20px;
        
        .stat-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          
          .el-icon {
            font-size: 24px;
            color: white;
          }
        }
        
        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .chart-section {
    margin-bottom: 20px;
    
    .chart-card {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .chart-container {
        height: 350px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .chart-placeholder {
          color: #909399;
          font-size: 16px;
        }
      }
    }
  }
  
  .analysis-section {
    .analysis-card {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      .card-header {
        font-weight: 600;
        color: #303133;
      }
      
      .analysis-content {
        padding: 16px 0;
        
        .growth-positive {
          color: #52c41a;
        }
        
        .growth-negative {
          color: #ff4d4f;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .statistics-report {
    padding: 12px;
    
    .report-header {
      .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;
      }
    }
    
    .stats-overview {
      .el-col {
        margin-bottom: 12px;
      }
    }
    
    .chart-section {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}
</style>